<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/12
 * Time: 11:15
 */

namespace app\admin\controller;

use Qiniu\Auth;
use app\admin\Controller;
use Qiniu\Storage\UploadManager;

class Common extends Controller
{

    public function uploadImg () {
        if ($this->request->method() == "POST") {
            if ($_FILES) {
                //图片
                $fFiles = $_FILES['pic'];
                $sk = "CDGB9523Xa5iPoSgwo6bUW-bBdLqi_o2vR04OKvH";
                $ak = "MhPSrJPHR31WjZ7uJ0Dgn1iQisrLwoR46G8z_4s5";
                $bucket = "chexun-imgs";
                $domain = 'http://download.bihuapp.com';

                $pathinfo = pathinfo($_FILES['pic']['name']);
                //halt($pathinfo);
                $ext = $pathinfo['extension'];

                $key = date('Y').date('m').date('YmdHis').rand(0,9999).'.'.$ext;
                $auth = new Auth($ak, $sk);

                $token = $auth->uploadToken($bucket);

                $uploadMgr = new UploadManager();

                $file = $uploadMgr->putFile($token,$key, $fFiles['tmp_name']);
                if ($file === null) {
                    $data = [
                        "success" => 0,
                        "msg" => "上传失败",
                        "data" => [],
                    ];
                } else {
                    //返回图片的完整URL
                    $data = [
                        "success" => 1,
                        "msg" => "上传完成",
                        'url' => $domain . '/' . $file[0]['key'],
                    ];
                }
                return json($data);

            }
        }


    }

}